package com.example.day02;

import android.os.Bundle;
import android.widget.FrameLayout;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;

import com.example.day02.fragment.FuFragment;
import com.example.day02.fragment.HomeFragment;
import com.google.android.material.tabs.TabLayout;

public class MainActivity extends AppCompatActivity {

    private TextView mBarText;
    private FrameLayout mMainFrame;
    private TabLayout mMainTab;
    private FragmentManager supportFragmentManager;
    private HomeFragment homeFragment;
    private FuFragment fuFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initViews();
    }

    private void initViews() {
        mBarText = findViewById(R.id.bar_text);
        mMainFrame = findViewById(R.id.main_frame);
        mMainTab = findViewById(R.id.main_tab);
        supportFragmentManager = getSupportFragmentManager();
        mMainTab.addTab(mMainTab.newTab().setText("首页"));
        mMainTab.addTab(mMainTab.newTab().setText("我的"));
        homeFragment = new HomeFragment();
        fuFragment = new FuFragment();
        supportFragmentManager.beginTransaction().add(R.id.main_frame,homeFragment).show(homeFragment).add(R.id.main_frame,fuFragment).hide(fuFragment).commit();
        mBarText.setText("首页");
        mMainTab.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                switch (tab.getPosition()){
                    case 0:
                            supportFragmentManager.beginTransaction().show(homeFragment).hide(fuFragment).commit();
                            mBarText.setText("首页");
                        break;
                    case 1:
                        supportFragmentManager.beginTransaction().show(fuFragment).hide(homeFragment).commit();
                        mBarText.setText("我的");
                        break;
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }
}
